<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="1080px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">				
				<el-tabs v-model="activeName" @tab-click="tabClick">
					<el-tab-pane v-if="mode != 'account'"  label="基础设置" name="1">
						<el-form-item label="门店编号" prop="storeCode">
						    <el-input class="w-[320px]" v-model="formData.storeCode" placeholder="请输入门店编号" />
						</el-form-item>
						<el-form-item label="门店名称" prop="storeName">
						    <el-input class="w-[320px]" v-model="formData.storeName" placeholder="请输入门店名称" />
						</el-form-item>
						<el-form-item label="联系人" prop="contact">
						    <el-input class="w-[320px]" v-model="formData.contact" placeholder="请输入联系人" />
						</el-form-item>
						<el-form-item label="联系手机号" prop="mobile">
						    <el-input class="w-[320px]" v-model="formData.mobile" type="number" placeholder="请输入联系手机号" />
						</el-form-item>						
						<el-form-item label="门店地址" prop="province">
						    <area-select v-model:province="formData.province" v-model:city="formData.city" v-model:district="formData.district" :checkStrictly="true" :width="'320px'" />
						</el-form-item>
						<el-form-item label="详细地址" prop="address">
						    <el-input  class="ls-input w-[320px]" v-model="formData.address" show-word-limit placeholder="请输入详情地址" >
						        <template #append>
						            <el-button  @click="onMapSearch">搜索地图</el-button>
						        </template>
						    </el-input>
						</el-form-item>
						<!-- 地图定位 -->
						<el-form-item label="地图定位" prop="password_confirm">
							<div class="tencent-map">
								<qq-map :tencentMap="tencentMap" v-if="tencentMap" :extendData="extendData" @click="clickQqMap" :centerLocation="initCenter"></qq-map>
							</div>						    
						</el-form-item>						
					</el-tab-pane>
					
				    <el-tab-pane v-if="mode != 'account'" label="经营设置" name="2">
						<el-form-item label="定价方式" prop="priceType">
							<el-radio-group v-model="formData.priceType">
							    <el-radio :label="0">总部定价</el-radio>
							    <el-radio :label="1">门店定价</el-radio>							    
							</el-radio-group>
						</el-form-item>
						<el-form-item label="营业周天" prop="weekdays">
						    <el-checkbox-group v-model="weekdayChecked">
						        <el-checkbox v-for="weekday in weekdayList" :label="weekday.key" :key="weekday.key">{{
						            weekday.label
						        }}</el-checkbox>
						    </el-checkbox-group>
						</el-form-item>
						
						<el-form-item label="营业时段" prop="businessStartTime">
							<div class="w-[360px]">
								<el-time-picker										
									class="ls-input"
									is-range
									v-model="businessTime"
									range-separator="至"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									placeholder="选择时间范围"
								>
								</el-time-picker>
							</div>
						</el-form-item>
						
						<el-form-item label="外卖配送距离" prop="deliveryDistance">
							<div class="w-[280px]">
								<el-input v-model="formData.deliveryDistance" type="number">
									<template #append>公里</template>
								</el-input>
							</div>
						</el-form-item>
						<el-form-item label="配送方式" prop="deliveryMethod">
							<el-checkbox-group v-model="deliveryMethod">
								<el-checkbox :label="0">自提</el-checkbox>
								<el-checkbox :label="1">外卖</el-checkbox>							    
							</el-checkbox-group>					
						</el-form-item>
						<el-form-item label="外卖起送价格" prop="deliveryPrice">
							<div class="w-[280px]">
								<el-input v-model="formData.deliveryPrice" type="number">
									<template #append>元</template>
								</el-input>
							</div>
						</el-form-item>
						<el-form-item label="外卖配送运费" prop="deliveryFreight">
							<div class="w-[280px]">
								<el-input v-model="formData.deliveryFreight" type="number">
									<template #append>元</template>
								</el-input>
							</div>						    
						</el-form-item>
						<el-form-item label="门店状态" prop="status">
							<div class="w-80">
							    <el-radio-group v-model="formData.status">
							    	<el-radio :label="0">停业</el-radio>
							    	<el-radio :label="1">营业</el-radio>							    
							    </el-radio-group>
							    <div class="form-tips">门店停业后，不能对外提供服务</div>
							</div>					
						</el-form-item>						
					</el-tab-pane>
					
				    <el-tab-pane v-if="mode != 'edit'" label="管理员账号设置" name="3">
						<el-form-item label="门店账号" prop="username">
							<div class="w-80">
							    <el-input class="w-[320px]" v-model="formData.username" placeholder="请输入账号" />
							    <div class="form-tips">门店账号和密码用于登录门店后台</div>
							</div>
						</el-form-item>
						<el-form-item label="登录密码" prop="password">
						    <div class="w-80">
						        <el-input class="w-[320px]" v-model.trim="formData.password" show-password placeholder="请输入密码" />
						        <div class="form-tips">门店账号和密码用于登录门店后台</div>
						    </div>
						</el-form-item>
						<el-form-item label="确认密码" prop="passwordConfirm">
						    <div class="w-80">
						        <el-input class="w-[320px]" v-model.trim="formData.passwordConfirm" show-password placeholder="请输入确认密码" />
						        <div class="form-tips">门店账号和密码用于登录门店后台</div>
						    </div>
						</el-form-item>
					</el-tab-pane>				    
				</el-tabs>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { apiMapRegionSearch } from '@/api/selffetchshop/selffetchshop'
import {  storeEdit, storeAdd, storeDetail } from '@/api/store/store'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'
import AreaSelect from '@/components/area-select/index.vue'
import QqMap from "@/components/qqmap/index.vue"
import { apiMapGet } from "@/api/setting/map"
import { timeFormat } from "@/utils/util"
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
	let titleName = "";
	if(mode.value == 'edit'){
		titleName = '编辑门店';
	}else if(mode.value == 'add'){
		titleName = '新增门店';
	}else if(mode.value == 'account'){
		titleName = '账号管理';
		activeName.value = '3';
	}
    return titleName;
})
const activeName = ref('1')
const tencentMap = ref<any>(undefined)
const initCenter = ref(undefined)
const extendData = ref([])
const weekdayChecked = ref([])
const deliveryMethod = ref([])
const businessTime: any[] = ref<[Date, Date]>([new Date().setHours(6, 0, 0), new Date().setHours(18, 0, 0)])
const weekdayList = ref([
        {
            key: 1,
            label: '周一'
        },
        {
            key: 2,
            label: '周二'
        },
        {
            key: 3,
            label: '周三'
        },
        {
            key: 4,
            label: '周四'
        },
        {
            key: 5,
            label: '周五'
        },
        {
            key: 6,
            label: '周六'
        },
        {
            key: 7,
            label: '周天'
        }
    ])
const formData = reactive({
    storeId: '',
    storeCode: '',
    storeName: '',
    contact: '',
    mobile: '',
    province: '',
    city: '',
    district: '',
    address: '',
    longitude: '',
    latitude: '',
    priceType: 0,
    weekdays: [],
    businessStartTime: '',
    businessEndTime: '',
    deliveryDistance: '',
    deliveryMethod: [],
    deliveryPrice: '',
    deliveryFreight: '',
    status: 0,
    remark: '',
	username: '',
	password: '',
	passwordConfirm: '',
})

const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}

const formRules = {
    storeId: [
        {
            required: true,
            message: '请输入主键ID',
            trigger: ['blur']
        }
    ],
    storeCode: [
        {
            required: true,
            message: '请输入门店编号',
            trigger: ['blur']
        }
    ],
    storeName: [
        {
            required: true,
            message: '请输入门店名称',
            trigger: ['blur']
        }
    ],
    contact: [
        {
            required: true,
            message: '请输入联系人',
            trigger: ['blur']
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入联系手机号',
            trigger: ['blur']
        }
    ],
    province: [
        {
            required: true,
            message: '请选择门店地址',
            trigger: ['blur']
        }
    ],    
    address: [
        {
            required: true,
            message: '请输入详细地址',
            trigger: ['blur']
        }
    ],    
    priceType: [
        {
            required: true,
            message: '请选择定价方式',
            trigger: ['blur']
        }
    ],
    weekdays: [
        {
            required: true,
            message: '请选择营业周天',
            trigger: ['blur']
        }
    ],
    businessStartTime: [
        {
            required: true,
            message: '请选择营业时段',
            trigger: ['blur']
        }
    ],    
    deliveryDistance: [
        {
            required: true,
            message: '请输入外卖配送距离',
            trigger: ['blur']
        }
    ],
    deliveryMethod: [
        {
            required: true,
            message: '请选择配送方式',
            trigger: ['blur']
        }
    ],
    deliveryPrice: [
        {
            required: true,
            message: '请输入外卖起送价格',
            trigger: ['blur']
        }
    ],
    deliveryFreight: [
        {
            required: true,
            message: '请输入外卖配送运费',
            trigger: ['blur']
        }
    ],
    status: [
        {
            required: true,
            message: '请选择门店状态',
            trigger: ['blur']
        }
    ],
	username: [
	    {
	        required: true,
	        message: '请输入账号',
	        trigger: ['blur']
	    }
	],
	password: [
	    {
	        required: true,
	        message: '请输入密码',
	        trigger: 'blur'
	    }
	] as any[],
	passwordConfirm: [
	    {
	        required: true,
	        message: '请再次输入密码',
	        trigger: 'blur'
	    },
	    {
	        validator: passwordConfirmValidator,
	        trigger: 'blur'
	    }
	] as any[]
    
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = { ...formData }	
	console.log("data:"+JSON.stringify(data))
	//return	
    mode.value == 'add' ? await storeAdd(data) : await storeEdit(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const tabClick = (tab:any,event:any) => {
	console.log(tab, event);
}

const setFormData = async (data: Record<string, any>) => {
	formRules.password = []
	formRules.passwordConfirm = [
	    {
	        validator: passwordConfirmValidator,
	        trigger: 'blur'
	    }
	]	
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
	weekdayChecked.value = data.weekdays.split(',').map((item: string) => Number(item))	
	deliveryMethod.value = data.deliveryMethod.split(',').map((item: string) => Number(item))	
    const date = new Date().toDateString()
    const dateFormat = timeFormat(Date.parse(date), 'yyyy-mm-dd')
    businessTime.value = [
        new Date(dateFormat + ' ' + data.businessStartTime),
        new Date(dateFormat + ' ' + data.businessEndTime)
    ]
    initCenter.value = {lat: formData.latitude, lng: formData.longitude, content: formData.address}
}

const getDetail = async (row: Record<string, any>) => {
    const data = await storeDetail({
        storeId: row.storeId
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

watch(weekdayChecked, (value, oldValue) => {
    formData.weekdays = value.slice().sort((a, b) => a - b).join(',')
}, { deep: true });

watch(deliveryMethod, (value, oldValue) => {
    formData.deliveryMethod = value.slice().sort((a, b) => a - b).join(',')
}, { deep: true });

watch(businessTime, (value, oldValue) => {
    formData.businessStartTime =  timeFormat(Date.parse(value[0]), 'hh:MM:ss')
    formData.businessEndTime =  timeFormat(Date.parse(value[1]), 'hh:MM:ss')
    //console.log(formData, "formDataformData", value)
})

const getApiMapGet = async () => {
    let map = await apiMapGet()
    tencentMap.value = map.tencentMapKey
}

// 地图搜索
const onMapSearch = () => {
        if (!tencentMap.value) {
            return feedback.msgError('地图未加载完成')
        }
        apiMapRegionSearch({
            keyword: encodeURI(formData.address),
            boundary: `region(${formData.district ?? formData.city}, 0)`,
            key: tencentMap.value!
        }).then(({ data }) => {
                if (!data.length) {
                    return feedback.msgError(`没有找到“${formData.address}”的相关地点`)
                } else {
                    extendData.value = []
                    formData.longitude = data[0].location.lng
                    formData.latitude = data[0].location.lat
                    console.log(formData)
                    data.map(item => {
                        extendData.value.push({
                            id: item.id,
                            styleId: 'marker',
                            position:  { lat: item.location.lat, lng: item.location.lng },
                            properties: {
                                title: item.title
                            },
                            content: item.title
                        })
                    })
                }
        }).catch(err => {
            feedback.msgError('地图搜索出现了点问题，请重新尝试。')
        })
}

const clickQqMap = (e) => {
    formData.longitude = e.latLng.lng
    formData.latitude = e.latLng.lat
    console.log(formData, "formDataformData")
}

defineExpose({
    open,
    setFormData,
    getDetail
})
getApiMapGet()
</script>
<style lang="scss" scoped>
.tencent-map {
	width: 680px;
	height: 430px;
}
</style>
